package com.erp.erp_ui.warehouse.service;

import com.erp.enums.*;
import com.erp.erp_entitys.warehouse.entity.*;
import com.erp.erp_entitys.warehouse.req.*;
import com.erp.erp_entitys.warehouse.req.SelectStockReq;
import com.erp.erp_entitys.warehouse.rsp.*;
import com.erp.erp_servers.Ftp.IFtpService;
import com.erp.erp_servers.warehouse.*;
import com.erp.erp_ui.money.req.OperationReq;
import com.erp.erp_ui.warehouse.enums.DataIsValidEnum;
import com.erp.erp_ui.warehouse.enums.DataSourceTitleEnum;
import com.erp.erp_ui.warehouse.enums.TransferTypeEnum;
import com.erp.erp_ui.warehouse.req.*;
import com.erp.erp_ui.warehouse.vo.*;
import com.erp.utils.*;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @ClassName : TransferService
 * @Description : 调拨业务逻辑层
 * @Author : lst
 * @Date: 2020-07-30 15:38
 */
@Service
public class TransferService {

    /**
     * 日志
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(TransferService.class);

    /**
     * 调拨接口
     */
    private final ITransferService transferService;

    /**
     * 调拨明细接口
     */
    private final ITransferDetailService transferDetailService;

    /**
     * 库存接口
     */
    private final IStockService stockService;

    /**
     * 库存明细接口
     */
    private final IStockDetailService stockDetailService;

    /**
     * 附件接口
     */
    private final IAnnexService annexService;

    /**
     * 临时附件接口
     */
    private final ITempAnnexService tempAnnexService;

    /**
     * FTP接口
     */
    private final IFtpService ftpService;


    /**
     * 其它出库接口
     */
    private final IOtherOutStockService otherOutStockService;


    @Autowired
    public TransferService(ITransferService transferService,
                           ITransferDetailService transferDetailService,
                           IStockService stockService,
                           IStockDetailService stockDetailService,
                           IAnnexService annexService,
                           ITempAnnexService tempAnnexService,
                           IFtpService ftpService,
                           IOtherOutStockService otherOutStockService) {
        this.transferService = transferService;
        this.transferDetailService = transferDetailService;
        this.stockService = stockService;
        this.stockDetailService = stockDetailService;
        this.annexService = annexService;
        this.tempAnnexService = tempAnnexService;
        this.ftpService = ftpService;
        this.otherOutStockService = otherOutStockService;
    }

    /**
     * 调拨分页
     *
     * @param req 入参实体
     * @return 分页对象集合
     */
    public PageInfo<TransferVo> getListByPage(TransferReq req) {
        //初始化入参实体
        QueryTransferReq queryTransferReq = new QueryTransferReq();
        //参数赋值
        BeanUtils.copyProperties(req, queryTransferReq);
        if (StringUtils.isNotEmpty(req.getBillNo())) {
            //去掉前后空格
            queryTransferReq.setBillNo(req.getBillNo().trim());
        }
        //调用查询接口获取调拨集合
        List<TransferEntity> transfers = transferService.queryTransferList(queryTransferReq);
        //获取分页信息
        PageInfo transferPage = new PageInfo(transfers);
        //初始化回参对象集合
        List<TransferVo> transferVos = new ArrayList<>();
        //遍历处理返回信息
        for (TransferEntity transfer : transfers) {
            TransferVo transferVo = new TransferVo();
            //对象赋值
            BeanUtils.copyProperties(transfer, transferVo);
            //处理调拨类型(1:合同调拨 2:合同置空)
            transferVo.setTypeStr(TransferTypeEnum.getDescById(transfer.getType()));
            //调拨时间转换
            transferVo.setTime(DateUtils.format(transfer.getTime(), DateUtils.DATE_PATTERN));
            //创建时间转换
            transferVo.setCreateDate(DateUtils.format(transfer.getCreateDate(), DateUtils.DATE_PATTERN));
            //状态转换
            transferVo.setStatusStr(OperationStatusEnum.getDescById(transfer.getStatus()));

            transferVos.add(transferVo);
        }

        transferPage.setList(transferVos);

        return transferPage;
    }

    /**
     * 设置仓库信息
     *
     * @param warehouseInfos 仓库信息集合
     * @param warehouseId    仓库编码
     */
    private String setWarehouse(List<DictionaryInfoRsp> warehouseInfos, String warehouseId) {
        if (CollectionUtils.isEmpty(warehouseInfos) || StringUtils.isBlank(warehouseId)) {
            return null;
        }
        for (DictionaryInfoRsp warehouseInfo : warehouseInfos) {
            if (warehouseInfo.getCode().equals(warehouseId)) {
                return warehouseInfo.getName();
            }
        }
        return null;
    }

    /**
     * 删除调拨数据(修改数据有效性)
     *
     * @param id     调拨id
     * @param status 状态(1.草稿箱 2.待批箱 3.已批箱 4.完成箱 5.垃圾箱)
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteTransfer(Integer id, Integer status) {
        if (null == id) {
            return;
        }
        TransferEntity transfer = new TransferEntity();
        transfer.setId(id);
        if (OperationStatusEnum.DRAFT_BOX.getId() == status) {
            //草稿箱删除：数据设为垃圾箱
            transfer.setStatus(OperationStatusEnum.TRASH_CAN.getId());
            transferService.update(transfer);
            return;
        } else if (OperationStatusEnum.TRASH_CAN.getId() == status) {
            //垃圾箱删除：数据回退到草稿箱
            transfer.setStatus(OperationStatusEnum.DRAFT_BOX.getId());
            transferService.update(transfer);
        }

        //获取调拨明细数据
        TransferDetailEntity transferDetail = new TransferDetailEntity();
        transferDetail.setTransferId(id);
        transferDetail.setValid(DataIsValidEnum.VALID.getId());
        //获取调拨明细
        List<TransferDetailEntity> transferDetails = transferDetailService.queryAll(transferDetail);
        if (CollectionUtils.isEmpty(transferDetails)) {
            //没有调拨明细,只删除调拨主表数据
            return;
        }
        for (TransferDetailEntity detail : transferDetails) {
            //调拨数量不为空
            if (StringUtil.isNotEmpty(detail.getTransferQuantity())) {
                //库存id
                int stockId = detail.getStockId();
                StockEntity stockEntity = stockService.getStockById(stockId);
                //调拨数量
                BigDecimal transferQuantity = detail.getTransferQuantity();
                //获取库存id
                StockEntity stock = new StockEntity();
                //设置库存id
                stock.setId(stockId);
                //获取库存调拨申请数量
                BigDecimal transferApplyQuantity = stockEntity.getTransferApplyQuantity();
                //获取库存可申请数量
                BigDecimal canApplyQuantity = stockEntity.getCanApplyQuantity();
                //只有垃圾箱和草稿箱有删除按钮,草稿箱删除：数据回退，状态为垃圾箱 垃圾箱删除：库存调拨申请数量和可申请数量减掉调拨数量，状态为草稿箱
                //库存明细修改
                StockDetailEntity stockDetail = new StockDetailEntity();
                stockDetail.setId(detail.getStockDetailId());

                //将调拨明细修改
                TransferDetailEntity transferReq = new TransferDetailEntity();
                transferReq.setId(detail.getId());

                if (OperationStatusEnum.DRAFT_BOX.getId() == status) {
                    //草稿箱删除：数据回退，状态为垃圾箱
                    //回退调拨申请数量
                    stock.setTransferApplyQuantity(transferApplyQuantity.subtract(transferQuantity));
                    //可申请数量
                    if (StringUtil.isNotEmpty(canApplyQuantity)) {
                        //回退可申请数量
                        stock.setCanApplyQuantity(canApplyQuantity.add(transferQuantity));
                    } else {
                        //回退可申请数量
                        stock.setCanApplyQuantity(transferQuantity);
                    }

                    //将库存明细设为失效
                    stockDetail.setValid(DataIsValidEnum.INVALID.getId());

                    //将调拨明细设为失效
                    transferReq.setValid(DataIsValidEnum.INVALID.getId());

                } else if (OperationStatusEnum.TRASH_CAN.getId() == status) {
                    //垃圾箱删除：库存调拨申请数量和可申请数量减掉调拨数量，状态为草稿箱
                    if (canApplyQuantity.compareTo(transferQuantity) > -1) {
                        //可申请数量大于等于调拨数量
                        if (StringUtil.isNotEmpty(transferApplyQuantity)) {
                            stock.setTransferApplyQuantity(transferApplyQuantity.add(transferQuantity));
                        } else {
                            stock.setTransferApplyQuantity(transferQuantity);
                        }
                        //设置可申请数量
                        stock.setCanApplyQuantity(canApplyQuantity.subtract(transferQuantity));
                    } else {
                        //可申请数量小于调拨数量,不能调拨
                        return;
                    }

                    //将库存明细设为有效
                    stockDetail.setValid(DataIsValidEnum.VALID.getId());

                    //将调拨明细设为有效
                    transferReq.setValid(DataIsValidEnum.VALID.getId());
                }
                //更新库存数量
                stockService.update(stock);
                //修改库存明细状态
                stockDetailService.update(stockDetail);
                //修改调拨明细状态
                transferDetailService.update(transferReq);
            }
        }
        return;
    }

    /**
     * 获取调拨详情信息
     *
     * @param id   调拨id
     * @param flag true:修改 false:详情
     * @return
     */
    public TransferDetailVo getTransferDetailInfo(Integer id, boolean flag) {
        //初始化回参实体
        TransferDetailVo vo = new TransferDetailVo();
        if (null == id) {
            return vo;
        }

        //第一步：获取主表信息
        TransferEntity transfer = transferService.getTransferById(id);
        if (null == transfer || null == transfer.getId()) {
            return vo;
        }
        //赋值
        BeanUtils.copyProperties(transfer, vo);
        //设置调拨时间
        vo.setTime(DateUtils.format(transfer.getTime(), DateUtils.DATE_PATTERN));
        //设置调拨类型
        vo.setTypeStr(TransferTypeEnum.getDescById(transfer.getType()));
        //设置创建时间
        vo.setCreateDate(DateUtils.format(transfer.getCreateDate(), DateUtils.DATE_PATTERN));

        //第二步：获取对应产品信息
        TransferDetailEntity transferDetail = new TransferDetailEntity();
        //设置调拨id
        transferDetail.setTransferId(id);
        //设置数据为有效
        transferDetail.setValid(DataIsValidEnum.VALID.getId());
        List<TransferDetailEntity> transferDetails = transferDetailService.queryAll(transferDetail);
        if (!CollectionUtils.isEmpty(transferDetails)) {
            List<TransferProductVo> productVos = transferDetails.stream().map(p -> {
                TransferProductVo productVo = new TransferProductVo();
                //赋值
                BeanUtils.copyProperties(p, productVo);

                //设置产品类型
                productVo.setProductTypeStr(ProductTypeEnum.getDescById(p.getProductType()));
                if (flag) {
                    //根据库存id获取最新调拨申请数量和可申请数量
                    StockEntity stock = stockService.getStockById(p.getStockId());
                    productVo.setCanTransferQuantity(stock.getCanApplyQuantity());
                    productVo.setStockQuantity(stock.getTransferApplyQuantity());
                }
                return productVo;
            }).collect(Collectors.toList());

            vo.setProductVos(productVos);
        }

        //第三步：获取附件信息
        AnnexEntity annex = new AnnexEntity();
        annex.setModuleId(ModuleTypeEnum.WAREHOUSE_TRANSFER.getId());
        annex.setParentId(id);
        List<AnnexEntity> annexList = annexService.queryAll(annex);
        if (!CollectionUtils.isEmpty(annexList)) {
            List<AnnexVo> annexVos = annexList.stream().map(p -> {
                AnnexVo annexVo = new AnnexVo();
                //赋值
                BeanUtils.copyProperties(p, annexVo);
                //上传时间转换
                annexVo.setUploadTime(DateUtils.format(p.getUploadTime(), DateUtils.DATE_TIME_PATTERN));
                //设置附件为旧附件,用以区分修改时附件状态
                annexVo.setNews(0);

                return annexVo;
            }).collect(Collectors.toList());

            vo.setAnnexVos(annexVos);
        }
        return vo;
    }

    /**
     * 调拨附件上传
     *
     * @param request
     * @param ftpPath    上传路径
     * @param operator   操作人
     * @param operatorNo 操作人编码
     * @return
     * @throws IOException
     */
    public List<AnnexVo> transferFileUpload(MultipartHttpServletRequest request, String ftpPath, String operator, String operatorNo) throws IOException {
        String fileType = "warehouse" + "/" + "transfer";
        List<UploadFile> fileList = ftpService.upload(request, fileType, ftpPath);

        List<AnnexVo> annexVos = new ArrayList<>();
        for (UploadFile uploadFile : fileList) {
            //初始化回参对象
            AnnexVo annexVo = new AnnexVo();
            if (uploadFile.isStatus()) {
                //上传成功,则添加记录到数据库
                TempAnnexEntity tempAnnex = new TempAnnexEntity();
                //设置模块id
                tempAnnex.setModuleId(ModuleTypeEnum.WAREHOUSE_TRANSFER.getId());
                //设置文件名称
                tempAnnex.setFileName(uploadFile.getOriginalFileName());
                //设置文件路径
                tempAnnex.setFilePath(uploadFile.getFtpPath() + "/" + uploadFile.getFileName());
                //设置上传建时间
                tempAnnex.setUploadTime(new Date());
                //设置修改时间
                tempAnnex.setUpdateTime(new Date());
                //设置操作人
                tempAnnex.setOperator(operator);
                //设置操作人编码
                tempAnnex.setOperatorNo(operatorNo);
                //设置附件有效
                tempAnnex.setValid(1);

                //调用接口新增附件
                int res = tempAnnexService.insert(tempAnnex);
                //如果新增成功,则返回新增的附件对象
                if (1 == res) {
                    //对象赋值
                    BeanUtils.copyProperties(tempAnnex, annexVo);
                    //日期转换
                    annexVo.setUploadTime(DateUtils.format(tempAnnex.getUploadTime(), DateUtils.DATE_TIME_PATTERN));
                    //设置上传状态
                    annexVo.setStatus(true);
                } else {
                    //新增失败,重新上传
                    //设置上传状态
                    annexVo.setStatus(false);
                }
            } else {
                //设置上传状态
                annexVo.setStatus(false);

            }
            //将返回对象实体放入集合中
            annexVos.add(annexVo);
        }
        return annexVos;
    }


    /**
     * 获取库存信息
     *
     * @param req 查询参数
     * @return 库存对象集合
     */
    public PageInfo<InStockProductVo> getStockInfo(InStockProductReq req) {
        //初始化回参集合
        List<InStockProductVo> productVos = new ArrayList<>();
        //获取库存信息，默认实际数量大于0,可申请数量大于0
        SelectStockReq selectStockReq = new SelectStockReq();
        //赋值
        BeanUtils.copyProperties(req, selectStockReq);
        //销售合同号
        if(StringUtils.isNotEmpty(req.getContractNo())){
            //去除前后空格
            selectStockReq.setContractNo(req.getContractNo().trim());
        }
        //产品编码
        if(StringUtils.isNotEmpty(req.getProductCode())){
            //去除前后空格
            selectStockReq.setProductCode(req.getProductCode().trim());
        }
        //规格编码
        if(StringUtils.isNotEmpty(req.getSpecificationCode())){
            //去除前后空格
            selectStockReq.setSpecificationCode(req.getSpecificationCode().trim());
        }
        //批次号
        if(StringUtils.isNotEmpty(req.getLotNo())){
            //去除前后空格
            selectStockReq.setLotNo(req.getLotNo().trim());
        }
        //可申请数量必须大于零
        selectStockReq.setZeroCanApplyQuantity(0);
        //查询库存信息
        List<StockEntity> stocks = stockService.getStockListByQuery(selectStockReq);
        PageInfo stockPageInfo = new PageInfo(stocks);
        if (stocks.isEmpty()) {
            stockPageInfo.setList(productVos);
            return stockPageInfo;
        }
        for (StockEntity stock : stocks) {
            //初始化回参实体
            InStockProductVo productVo = new InStockProductVo();
            //赋值
            BeanUtils.copyProperties(stock, productVo);
            //设置调拨数量(默认为0)
            productVo.setTransferQuantity(new BigDecimal("0"));
            //设置库存数量
            productVo.setStockQuantity(stock.getRealQuantity());
            //置空销售单价默认为0
            productVo.setSalesUnitPrice(new BigDecimal("0"));

            //获取允许调拨数量(合同置空:取库存可申请数量)
            productVo.setCanTransferQuantity(stock.getCanApplyQuantity());

            //设置库存id
            productVo.setStockId(stock.getId());
            //设置新仓库(默认等于源仓库)
            productVo.setNewWarehouseCode(stock.getWarehouseCode());
            productVo.setNewWarehouseName(stock.getWarehouseName());

            //设置产品类型
            productVo.setProductTypeStr(ProductTypeEnum.getDescById(stock.getProductType()));
            //设置成本单价
            productVo.setCostUnitPrice(stock.getProductUnitPrice());
            //设置金额默认为0,计算方式为:(成本单价+分摊费用单价)*调拨数量
            productVo.setMoney(new BigDecimal("0.00"));

            productVos.add(productVo);
        }

        stockPageInfo.setList(productVos);
        return stockPageInfo;
    }

    /**
     * 获取销售合同主表信息
     *
     * @param req 查询条件
     * @return 销售合同信息
     */
    public PageInfo<ImportContractInfoVo> getStockBySaleContract(ImportContractInfoReq req) {
        //通过销售合同导入库存数据
        //初始化查询条件
        ContractInfoReq infoReq = new ContractInfoReq();
        //查询条件赋值
        BeanUtils.copyProperties(req, infoReq);
        //销售合同号
        if (StringUtils.isNotEmpty(req.getBillNo())) {
            //去掉前后空格
            infoReq.setBillNo(req.getBillNo().trim());
        }
        //客户合同号
        if (StringUtils.isNotEmpty(req.getCustomerContactNo())) {
            //去掉前后空格
            infoReq.setCustomerContactNo(req.getCustomerContactNo().trim());
        }
        //客户名称
        if (StringUtils.isNotEmpty(req.getCustomerName())) {
            //去掉前后空格
            infoReq.setCustomerName(req.getCustomerName().trim());
        }
        //获取查询结果
        List<ContractInfoRsp> contractInfos = stockService.getContractAndStockInfo(infoReq);
        //获取分页信息
        PageInfo contractInfoPageInfo = new PageInfo(contractInfos);
        //封装查询结果
        List<ImportContractInfoVo> contractInfoVos = new ArrayList<>();
        if (CollectionUtils.isEmpty(contractInfos)) {
            contractInfoPageInfo.setList(contractInfoVos);
            return contractInfoPageInfo;
        }
        for (ContractInfoRsp info : contractInfos) {
            //初始化回参实体
            ImportContractInfoVo contractInfoVo = new ImportContractInfoVo();
            //赋值
            BeanUtils.copyProperties(info, contractInfoVo);
            //合同id
            contractInfoVo.setContractId(info.getId());
            //创建时间转换
            contractInfoVo.setCreateDate(DateUtils.format(info.getCreateDate(), DateUtils.DATE_PATTERN));
            //出运日期转换
            contractInfoVo.setCarryDate(DateUtils.format(info.getCarryDate(), DateUtils.DATE_PATTERN));

            contractInfoVos.add(contractInfoVo);
        }
        contractInfoPageInfo.setList(contractInfoVos);
        return contractInfoPageInfo;
    }


    /**
     * 获取销售合同产品信息
     *
     * @param id 销售合同id
     * @return 销售合同产品对象集合
     */
    public PageInfo<ImportContractProductInfoVo> getSaleContractProductByPage(Integer id) {
        //通过销售合同导入库存数据
        List<ImportContractInfoRsp> contractInfos = stockService.getContractProductInfo(id);
        //初始化回参对象集合
        List<ImportContractProductInfoVo> infoVos = new ArrayList<>();
        //获取分页信息
        PageInfo pageInfo = new PageInfo(contractInfos);
        if (CollectionUtils.isEmpty(contractInfos)) {
            pageInfo.setList(infoVos);
            return pageInfo;
        }
        for (ImportContractInfoRsp rsp : contractInfos) {
            ImportContractProductInfoVo infoVo = new ImportContractProductInfoVo();
            //字段赋值
            BeanUtils.copyProperties(rsp, infoVo);
            //设置销售合同号id
            infoVo.setContractId(rsp.getContractId());
            //设置产品类型(1:成品 2:配件 3:料件)
            infoVo.setProductTypeStr(ProductTypeEnum.getDescById(rsp.getProductType()));
            //设置成本单价
            infoVo.setCostUnitPrice(rsp.getProductUnitPrice());
            //库存可申请数量
            BigDecimal canApplyQuantity = new BigDecimal("0");
            if (StringUtil.isNotEmpty(rsp.getCanApplyQuantity())) {
                canApplyQuantity = rsp.getCanApplyQuantity();
            }
            //已调拨数量
            BigDecimal transferNum = new BigDecimal("0");
            if (StringUtil.isNotEmpty(rsp.getTransferNum())) {
                transferNum = rsp.getTransferNum();
            }
            //产品数量
            BigDecimal productNum = new BigDecimal("0");
            if (StringUtil.isNotEmpty(rsp.getSalesQuantity())) {
                productNum = rsp.getSalesQuantity();
            }

            //外销产品剩余可调拨数量
            BigDecimal num = productNum.subtract(transferNum);
            //允许调拨数量
            infoVo.setCanTransferQuantity(num);
            //调拨数量默认为零
            infoVo.setTransferQuantity(new BigDecimal("0"));

            infoVos.add(infoVo);
        }
        pageInfo.setList(infoVos);
        return pageInfo;
    }

    /**
     * 获取组装库存数据
     *
     * @param contractInfos 销售合同关联库存数据对象集合
     * @return
     */
    private List<ImportContractProductInfoVo> getAssemblyContractProductInfoVo(List<ImportContractInfoRsp> contractInfos) {
        //初始化回参对象集合
        List<ImportContractProductInfoVo> infoVos = new ArrayList<>();
        for (ImportContractInfoRsp rsp : contractInfos) {
            ImportContractProductInfoVo infoVo = new ImportContractProductInfoVo();
            //字段赋值
            BeanUtils.copyProperties(rsp, infoVo);
            //设置销售合同号id
            infoVo.setContractId(rsp.getContractId());
            //设置产品类型(1:成品 2:配件 3:料件)
            infoVo.setProductTypeStr(ProductTypeEnum.getDescById(rsp.getProductType()));
            //设置成本单价
            infoVo.setCostUnitPrice(rsp.getProductUnitPrice());
            //获取销售数量
            BigDecimal salesQuantity = rsp.getSalesQuantity();
            if (StringUtil.isNotEmpty(salesQuantity)) {
                //获取实际数量
                BigDecimal newRealQuantity = getStockRealQuantity(rsp);
                //设置可调拨数量
                if (-1 == newRealQuantity.compareTo(BigDecimal.ZERO)) {
                    infoVo.setCanTransferQuantity(salesQuantity);
                } else {
                    infoVo.setCanTransferQuantity(newRealQuantity);
                }
            }
            infoVos.add(infoVo);
        }

        return infoVos;
    }

    /**
     * 获取实际可用数量
     *
     * @param rsp 销售信息
     * @return 实际可用数量
     */
    private BigDecimal getStockRealQuantity(ImportContractInfoRsp rsp) {
        //初始化查询参数
        StockEntity req = new StockEntity();
        //获取合同号
        String contractNo = rsp.getNewContractNo();
        //产品编码
        req.setProductCode(rsp.getProductCode());
        //规格编码
        req.setSpecificationCode(rsp.getSpecificationCode());
        List<StockEntity> stocks = stockService.getStockListByStock(req);
        if (CollectionUtils.isEmpty(stocks)) {
            return new BigDecimal("0");
        }
        //初始化数量
        BigDecimal realQuantity = new BigDecimal("0");
        BigDecimal transferApplyQuantity = new BigDecimal("0");
        for (StockEntity stock : stocks) {
            if (StringUtils.isBlank(stock.getContractNo())) {
                //合同号为空,累计调拨申请数量
                if (StringUtil.isNotEmpty(stock.getTransferApplyQuantity())) {
                    transferApplyQuantity = transferApplyQuantity.add(stock.getTransferApplyQuantity());
                }
            } else if (stock.getContractNo().equals(contractNo)) {
                //合同号不为空,且等当前合同号,累计实际数量
                if (StringUtil.isNotEmpty(stock.getRealQuantity())) {
                    realQuantity = realQuantity.add(stock.getRealQuantity());
                }
            }

        }
        BigDecimal res = rsp.getSalesQuantity().subtract(realQuantity).subtract(transferApplyQuantity);
        //查询历史调拨数量(状态为草稿箱)
        TransferDetailEntity transferDetail = new TransferDetailEntity();
        //设置新的合同号
        transferDetail.setNewContractNo(contractNo);
        //设置库存id
        transferDetail.setStockId(rsp.getStockId());
        //获取调拨数据(状态为草稿箱)
        List<TransferDetailEntity> detailList = transferDetailService.getTransferDetail(transferDetail);
        if (CollectionUtils.isEmpty(detailList)) {
            return res;
        }
        //已经调拨，但是在草稿箱的调拨数量
        BigDecimal transferNums = new BigDecimal("0");
        for (TransferDetailEntity detail : detailList) {
            if (StringUtil.isNotEmpty(detail.getTransferQuantity())) {
                transferNums = transferNums.add(detail.getTransferQuantity());
            }
        }

        return res.subtract(transferNums);
    }


    /**
     * 调拨,合同置空接口
     *
     * @param req      新增参数
     * @param creator  创建人
     * @param createNo 创建人编码
     * @param type     调拨类型(1:合同调拨 2:合同置空)
     * @return 调拨id
     * @throws ParseException
     */
    public Integer insertTransfer(AddTransferReq req, String creator, String createNo, Integer type) throws ParseException {
        //初始化调拨对象
        TransferEntity transfer = new TransferEntity();
        //赋值
        BeanUtils.copyProperties(req, transfer);
        //设置调拨类型(1:合同调拨 2:合同置空)
        transfer.setType(type);
        //设置调拨时间
        transfer.setTime(DateUtils.convertStringToDate(req.getTime(), DateUtils.DATE_PATTERN));
        //设置创建人
        transfer.setCreator(creator);
        //设置创建人编码
        transfer.setCreatorNo(createNo);
        //保存后进草稿箱
        transfer.setStatus(OperationStatusEnum.DRAFT_BOX.getId());
        //设置数据有效性(0:无效 1:有效)
        transfer.setValid(DataIsValidEnum.VALID.getId());

        if (null == req.getId()) {
            //新增
            //设置创建时间
            transfer.setCreateDate(new Date());
            //调用接口新增调拨
            return transferService.insert(transfer) == 1 ? transfer.getId() : null;
        } else {
            //修改
            return transferService.update(transfer) == 1 ? transfer.getId() : null;
        }

    }

    /**
     * 根据销售合同id集合获取库存集合信息
     *
     * @param ids 销售id集合
     * @return 库存集合信息
     */
    public List<ImportContractProductInfoVo> getStockListByContractIds(Integer[] ids) {
        List<ImportContractProductInfoVo> infoVos = new ArrayList<>();
        if (null == ids || 0 == ids.length) {
            return infoVos;
        }
        List<ImportContractInfoRsp> infoRspList = stockService.getStockListByContractIds(Arrays.asList(ids));
        if (CollectionUtils.isEmpty(infoRspList)) {
            return infoVos;
        }
        return getAssemblyContractProductInfoVo(infoRspList);
    }

    /**
     * 调拨明细新增以及更新库存可申请数量
     *
     * @param req        新增对象
     * @param transferId 调拨id
     */
    public void insertTransferDetail(AddTransferReq req, int transferId, String creator, String createNo) {
        if (!CollectionUtils.isEmpty(req.getTransferDetails())) {
            //获取修改调拨明细id集合
            List<Integer> newIds = new ArrayList<>();
            //新增调拨明细集合
            List<TransferDetailEntity> addTransferDetails = new ArrayList<>();
            for (AddTransferDetailReq detailReq : req.getTransferDetails()) {
                //初始化调拨明细对象
                TransferDetailEntity transferDetail = new TransferDetailEntity();
                //赋值
                BeanUtils.copyProperties(detailReq, transferDetail);
                //设置调拨id
                transferDetail.setTransferId(transferId);
                //业务员名称
                if(StringUtils.isNotEmpty(detailReq.getSalesman())){
                    transferDetail.setSalesmanName(detailReq.getSalesman());
                }
                //分摊费用单价
                BigDecimal shareCostPrice = new BigDecimal("0");
                if (StringUtil.isNotEmpty(detailReq.getShareCostPrice())) {
                    shareCostPrice = detailReq.getShareCostPrice();
                }
                //成本单价
                BigDecimal costUnitPrice = new BigDecimal("0");
                if (StringUtil.isNotEmpty(detailReq.getCostUnitPrice())) {
                    costUnitPrice = detailReq.getCostUnitPrice();
                }
                //获取调拨数量
                BigDecimal transferQuantity = new BigDecimal("0");
                if (StringUtil.isNotEmpty(detailReq.getTransferQuantity())) {
                    transferQuantity = detailReq.getTransferQuantity();
                }

                //设置金额 = (分摊费用单价 + 成本单价)*调拨数量
                if (StringUtil.isNotEmpty(costUnitPrice)) {
                    BigDecimal cost = shareCostPrice.add(costUnitPrice);
                    transferDetail.setMoney(cost.multiply(transferQuantity));
                }
                //获取托盘入数
                BigDecimal trayNumber = new BigDecimal("0");
                if (StringUtil.isNotEmpty(detailReq.getTrayNumber())) {
                    trayNumber = detailReq.getTrayNumber();
                }
                if (StringUtil.isNotEmpty(trayNumber)) {
                    //设置总托盘 = 调拨数量除以托盘入数
                    transferDetail.setTotalTray(transferQuantity.divide(trayNumber, 2, BigDecimal.ROUND_HALF_UP));
                } else {
                    transferDetail.setTotalTray(new BigDecimal("0"));
                }

                //设置数据有效性(0:无效 1:有效)
                transferDetail.setValid(DataIsValidEnum.VALID.getId());

                //库存明细新增
                int stockDetailId = addStockDetail(detailReq, req.getBillNo(), creator, createNo);
                //修改库存信息
                updateStockInfo(detailReq, req.getType());

                if (null == detailReq.getId()) {
                    //新增

                    //设置明细库存id
                    transferDetail.setStockDetailId(stockDetailId);
                    addTransferDetails.add(transferDetail);
                } else {
                    //修改

                    //获取明细id
                    newIds.add(detailReq.getId());
                    transferDetailService.update(transferDetail);
                }

            }

            //处理被删除的调拨明细
            handleBeenDeletedTransferDetail(req, transferId, newIds);

            if (!CollectionUtils.isEmpty(addTransferDetails)) {
                //调用接口保存调拨明细
                transferDetailService.insertTransferDetailList(addTransferDetails);
            }
        }
    }

    /**
     * 处理被删除的调拨明细
     *
     * @param req        调拨明细
     * @param transferId 调拨id
     * @param newIds     修改后未被删除的调拨明细id集合
     */
    private void handleBeenDeletedTransferDetail(AddTransferReq req, int transferId, List<Integer> newIds) {
        if (null != req.getId()) {
            //修改-找出被删除的调拨明细

            TransferDetailEntity transferDetail = new TransferDetailEntity();
            //设置调拨id
            transferDetail.setTransferId(transferId);
            //查询有效数据
            transferDetail.setValid(DataIsValidEnum.VALID.getId());
            //调用接口查询结果
            List<TransferDetailEntity> transferDetails = transferDetailService.queryAll(transferDetail);
            if (!CollectionUtils.isEmpty(transferDetails)) {
                //获取调拨明细id和库存明细id
                Map<String, Map<Integer, Integer>> stockIdAndStockDetailIdMap = getStockIdAndStockDetailIdMap(transferDetails);
                //获取调拨数量
                Map<Integer, BigDecimal> transferQuantityMap = getTransferQuantityMap(transferDetails);
                //获取id集合
                List<Integer> oldIds = transferDetails.stream().map(p -> p.getId()).collect(Collectors.toList());
                //找出被删除的id
                Collection collection = new ArrayList(oldIds);
                collection.removeAll(newIds);
                if (collection.size() > 0) {
                    //遍历删除被删除的明细
                    Iterator<Integer> ids = collection.iterator();
                    while (ids.hasNext()) {
                        int id = ids.next();
                        Integer stockId = stockIdAndStockDetailIdMap.get("stockIdMap").get(id);
                        //获取库存数据
                        StockEntity stock = stockService.getStockById(stockId);
                        //初始化库存对象
                        StockEntity stockReq = new StockEntity();
                        //设置修改主键
                        stockReq.setId(stockId);
                        //获取调拨数量
                        BigDecimal transferQuantity = transferQuantityMap.get(id);
                        if (null != req.getStatus() && req.getStatus().equals(OperationStatusEnum.APPROVED_BOX.getId())) {
                            //如果删除的是已批数据,则需要回退 实际数量、实际可用数量、可申请数量
                            stockReq.setRealQuantity(stock.getRealQuantity().add(transferQuantity));
                            stockReq.setRealAvailableQuantity(stock.getRealAvailableQuantity().add(transferQuantity));
                            stockReq.setCanApplyQuantity(stock.getCanApplyQuantity().add(transferQuantity));
                        } else {
                            //设置新的可申请数量
                            stockReq.setCanApplyQuantity(stock.getCanApplyQuantity().add(transferQuantity));
                            //设置新的调拨申请数量
                            stockReq.setTransferApplyQuantity(stock.getTransferApplyQuantity().subtract(transferQuantity));
                        }
                        //回退删除的调拨数量
                        stockService.update(stockReq);

                        TransferDetailEntity detail = new TransferDetailEntity();
                        detail.setId(id);
                        detail.setValid(DataIsValidEnum.INVALID.getId());
                        //将删除的调拨明细设为无效
                        transferDetailService.update(detail);
                        //通过调拨明细id获取库存库存明细id
                        Integer stockDetailId = stockIdAndStockDetailIdMap.get("stockDetailIdMap").get(id);
                        //将库存明细设为无效
                        StockDetailEntity stockDetail = new StockDetailEntity();
                        stockDetail.setId(stockDetailId);
                        stockDetail.setValid(DataIsValidEnum.INVALID.getId());
                        stockDetailService.update(stockDetail);
                    }
                }
            }
        }
    }

    /**
     * 获取库存id和库存明细id
     *
     * @param transferDetails 调拨明细对象
     * @return key为调拨明细id value为库存id和库存明细id
     */
    private Map<String, Map<Integer, Integer>> getStockIdAndStockDetailIdMap(List<TransferDetailEntity> transferDetails) {
        //获取集合大小
        int size = transferDetails.size();
        //库存明细id
        Map<Integer, Integer> stockDetailIdMap = new HashMap<>(size);
        //库存id
        Map<Integer, Integer> stockIdMap = new HashMap<>(size);
        for (TransferDetailEntity transferDetail : transferDetails) {
            stockDetailIdMap.put(transferDetail.getId(), transferDetail.getStockDetailId());
            stockIdMap.put(transferDetail.getId(), transferDetail.getStockId());
        }
        Map<String, Map<Integer, Integer>> map = new HashMap<>(3);
        map.put("stockDetailIdMap", stockDetailIdMap);
        map.put("stockIdMap", stockIdMap);
        return map;
    }

    /**
     * 获取调拨数量
     *
     * @param transferDetails 调拨明细对象
     * @return key为调拨明细id value为调拨数量
     */
    private Map<Integer, BigDecimal> getTransferQuantityMap(List<TransferDetailEntity> transferDetails) {
        //调拨数量
        Map<Integer, BigDecimal> transferQuantityMap = new HashMap<>(transferDetails.size());
        for (TransferDetailEntity transferDetail : transferDetails) {
            transferQuantityMap.put(transferDetail.getId(), transferDetail.getTransferQuantity());
        }
        return transferQuantityMap;
    }

    /**
     * 修改库存信息
     *
     * @param detailReq
     */
    private void updateStockInfo(AddTransferDetailReq detailReq, Integer type) {
        //获取调拨数量
        BigDecimal transferQuantity = detailReq.getTransferQuantity();
        //获取可申请数量
        BigDecimal canApplyQuantity = detailReq.getCanApplyQuantity();
        if (StringUtil.isNotEmpty(canApplyQuantity) && StringUtil.isNotEmpty(transferQuantity)) {
            //初始化库存对象
            StockEntity stock = new StockEntity();
            //设置修改id
            stock.setId(detailReq.getStockId());
            if (type == 2) {
                stock.setContractType(ContractTypeEnum.TO_BE_DETERMINED.getId());
                stock.setTransferApplyQuantity(new BigDecimal("0"));
                stock.setRealAvailableQuantity(detailReq.getTransferQuantity());
                stock.setContractNo("");
                stockService.updateStockInfo(stock);
            } else {
                BigDecimal oldTransferApplyQuantity = detailReq.getTransferApplyQuantity();
                stock.setCanApplyQuantity(canApplyQuantity.subtract(transferQuantity));
                stock.setTransferApplyQuantity(oldTransferApplyQuantity.add(transferQuantity));
                stockService.update(stock);
            }

        }
    }

    /**
     * 新增库存明细
     *
     * @param detailReq 调拨明细
     * @param billNo    单号
     * @param creator   创建人
     * @param createNo  创建人编码
     */
    private int addStockDetail(AddTransferDetailReq detailReq, String billNo, String creator, String createNo) {
        //初始化库存明细对象
        StockDetailEntity stockDetail = new StockDetailEntity();
        //赋值
        BeanUtils.copyProperties(detailReq, stockDetail);
        //设置标题
        stockDetail.setTitle(DataSourceTitleEnum.TRANSFER.getDesc());
        //设置单据编号
        stockDetail.setInvoiceNumber(billNo);
        //设置单价
        stockDetail.setUnitPrice(detailReq.getCostUnitPrice());
        //设置数量
        stockDetail.setQuantity(detailReq.getTransferQuantity());
        //设置模块id
        stockDetail.setModuleId(ModuleTypeEnum.WAREHOUSE_TRANSFER.getId());
        //设置创建人
        stockDetail.setInStorePerson(creator);
        //设置创建人编码
        stockDetail.setInStoreCode(createNo);
        //设置操作人
        stockDetail.setOperator(creator);
        //设置操作人编码
        stockDetail.setOperationCode(createNo);
        if (null == detailReq.getId()) {
            //新增

            //设置创建时间
            stockDetail.setCreateDate(new Date());
            //设置有效性
            stockDetail.setValid(DataIsValidEnum.VALID.getId());
            stockDetailService.insert(stockDetail);

        } else {
            //修改

            stockDetail.setId(detailReq.getStockDetailId());
            stockDetailService.update(stockDetail);
        }

        return stockDetail.getId();
    }


    /**
     * 调拨数量校验：
     * 1.调拨数量不能大于允许调拨数量
     * 2.调拨数量不能大于可申请数量
     *
     * @param req 新增入参实体
     * @return true:校验不通过 false:校验通过
     */
    private boolean checkTransferNum(AddTransferReq req) {
        for (AddTransferDetailReq detailReq : req.getTransferDetails()) {
            //获取调拨数量
            BigDecimal transferQuantity = detailReq.getTransferQuantity();
            //获取允许调拨数量
            BigDecimal canTransferQuantity = detailReq.getCanTransferQuantity();
            //获取可申请数量
            BigDecimal canApplyQuantity = detailReq.getCanApplyQuantity();
            boolean flag = checkTransferQuantity(transferQuantity, canTransferQuantity) && checkCanApplyQuantity(transferQuantity, canApplyQuantity);
            if (!flag) {
                return true;
            }
        }
        if (req.getType().equals(TransferTypeEnum.CONTRACT_TRANSFER.getId())) {
            //合同调拨,需要进行总调拨数校验
            List<String> strList = new ArrayList<>();
            //允许调拨数量
            Map<String, BigDecimal> canTransferQuantityMap = new HashMap<>();
            //调拨数量
            Map<String, BigDecimal> transferQuantityMap = new HashMap<>();
            for (AddTransferDetailReq detailReq : req.getTransferDetails()) {
                //销售合号
                String newContractNo = detailReq.getNewContractNo();
                //产品编码
                String productCode = detailReq.getProductCode();
                //规格编码
                String specificationCode = detailReq.getSpecificationCode();
                //允许调拨数量
                BigDecimal canTransferQuantity = detailReq.getCanTransferQuantity();
                //拨数量
                BigDecimal transferQuantity = detailReq.getTransferQuantity();
                //拼接字符串
                String data = newContractNo + "_" + productCode + "_" + specificationCode;
                if (!strList.contains(data)) {
                    strList.add(data);
                    canTransferQuantityMap.put(data, canTransferQuantity);
                    transferQuantityMap.put(data, transferQuantity);
                } else {
                    //同一批数据的调拨数量需要累加
                    BigDecimal newTransferQuantity = transferQuantityMap.get(data).add(transferQuantity);
                    transferQuantityMap.put(data, newTransferQuantity);
                }
            }
            for (String str : strList) {
                boolean flag = (transferQuantityMap.get(str).compareTo(canTransferQuantityMap.get(str)) == 1);
                if (flag) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 调拨数据校验：
     * 合同、仓库信息没有变动时,不能新增调拨
     * 校验该数据是否可以调拨 true:是 false:否
     *
     * @param req 新增的调拨数据
     * @return boolean
     */
    private boolean checkTransferData(AddTransferReq req) {
        for (AddTransferDetailReq detailReq : req.getTransferDetails()) {
            //获取老的合同号
            String contractNo = detailReq.getContractNo();
            //获取新的合同号
            String newContractNo = detailReq.getNewContractNo();
            //获取老的仓库id
            String warehouseId = detailReq.getWarehouseCode();
            //获取新的仓库id
            String newWarehouseId = detailReq.getNewWarehouseCode();
            //老合同号,新合同号,老仓库id,新仓库id都为空
            boolean allNullFlag = StringUtils.isBlank(contractNo)
                    && StringUtils.isBlank(newContractNo)
                    && StringUtils.isBlank(warehouseId)
                    && StringUtils.isBlank(newWarehouseId);
            //老合同号,新合同号 为空,老仓库id等于新仓库id
            boolean contractNullFlag = StringUtils.isBlank(contractNo)
                    && StringUtils.isBlank(newContractNo)
                    && (StringUtils.isNotBlank(warehouseId) && warehouseId.equals(newWarehouseId));
            //老合同号,新合同号,老仓库id,新仓库id都不为空,且彼此相等
            boolean allNotNullFlag = StringUtils.isNotBlank(contractNo)
                    && StringUtils.isNotBlank(newContractNo)
                    && contractNo.equals(newContractNo)
                    && StringUtils.isNotBlank(warehouseId)
                    && StringUtils.isNotBlank(newWarehouseId)
                    && warehouseId.equals(newWarehouseId);
            //合同号不为空且相等,仓库id为空
            boolean warehouseIdNullFlag = StringUtils.isNotBlank(contractNo)
                    && StringUtils.isNotBlank(newContractNo)
                    && contractNo.equals(newContractNo)
                    && StringUtils.isBlank(warehouseId)
                    && StringUtils.isBlank(newWarehouseId);
            //出现以上四种情况之一,不能调拨
            if (allNullFlag || contractNullFlag || allNotNullFlag || warehouseIdNullFlag) {
                return false;
            }
        }
        return true;
    }

    /**
     * 校验调拨数量是否小于等于允许调拨数量 true:是 false:否
     *
     * @param transferQuantity    调拨数量
     * @param canTransferQuantity 允许调拨数量
     * @return boolean
     */
    private boolean checkTransferQuantity(BigDecimal transferQuantity, BigDecimal canTransferQuantity) {
        if (StringUtil.isNotEmpty(transferQuantity) && StringUtil.isNotEmpty(canTransferQuantity)) {
            if (transferQuantity.compareTo(canTransferQuantity) < 1) {
                return true;
            }
            return false;
        }
        return false;
    }

    /**
     * 校验调拨数量是否小于等于可申请数量 true:是 false:否
     *
     * @param transferQuantity 调拨数量
     * @param canApplyQuantity 可申请数量
     * @return boolean
     */
    private boolean checkCanApplyQuantity(BigDecimal transferQuantity, BigDecimal canApplyQuantity) {
        if (StringUtil.isNotEmpty(transferQuantity) && StringUtil.isNotEmpty(canApplyQuantity)) {
            if (transferQuantity.compareTo(canApplyQuantity) < 1) {
                return true;
            }
            return false;
        }
        return false;
    }


    /**
     * 调拨审批
     *
     * @param transferId 调拨id
     * @return 审批结果
     */
    private R checkTransfer(Integer transferId) {
        //通过id获取调拨对象
        TransferEntity transfer = transferService.getTransferById(transferId);
        if (null == transfer) {
            LOGGER.warn("仓库管理-调拨-审核-获取调拨对象为空");
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }
        //初始化调拨明细对象
        TransferDetailEntity transferDetailReq = new TransferDetailEntity();
        //设置调拨id
        transferDetailReq.setTransferId(transferId);
        //设置数据有效性(0:无效 1:有效)
        transferDetailReq.setValid(DataIsValidEnum.VALID.getId());
        //查询调拨明细
        List<TransferDetailEntity> transferDetails = transferDetailService.queryAll(transferDetailReq);
        if (CollectionUtils.isEmpty(transferDetails)) {
            LOGGER.warn("仓库管理-调拨-审核-获取调拨明细对象为空");
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }
        for (TransferDetailEntity transferDetail : transferDetails) {
            //获取库存id
            Integer stockId = transferDetail.getStockId();
            //通过库存id获取库存信息
            StockEntity stockEntity = stockService.getStockById(stockId);
            //原始总托盘
            BigDecimal totalTray = stockEntity.getTotalTray();
            //调拨总托盘
            BigDecimal transferTotalTray = transferDetail.getTotalTray();
            //初始化库存对象
            StockEntity stock = new StockEntity();
            //设置库存id
            stock.setId(stockId);
            //更新后总托盘 = 原总托盘 - 调拨总托盘
            if (StringUtil.isNotEmpty(totalTray) && StringUtil.isNotEmpty(transferTotalTray)) {
                stock.setTotalTray(totalTray.subtract(transferTotalTray));
            }
            //原实际数量
            BigDecimal realQuantity = stockEntity.getRealQuantity();
            //原调拨申请数量
            BigDecimal transferApplyQuantity = new BigDecimal("0");
            if (StringUtil.isNotEmpty(stockEntity.getTransferApplyQuantity())) {
                transferApplyQuantity = stockEntity.getTransferApplyQuantity();
            }
            //调拨数量
            BigDecimal transferQuantity = transferDetail.getTransferQuantity();
            //更新后实际数量和实际可用数量 = 原实际数量 - 调拨数量
            if (StringUtil.isNotEmpty(realQuantity) && StringUtil.isNotEmpty(transferQuantity)) {
                BigDecimal quantity = realQuantity.subtract(transferQuantity);
                //更新实际数量
                stock.setRealQuantity(quantity);
                //更新实际可用数量
                stock.setRealAvailableQuantity(quantity);
                //更新调拨申请数量
                stock.setTransferApplyQuantity(transferApplyQuantity.subtract(transferQuantity));
            }

            //调用库存接口更新库存信息
            stockService.update(stock);

            //原库存新增明细(调拨流水)
            insertStockDetail(transferQuantity, transfer, stockEntity);

            //如果已存在同一类型库存数据(批次,产品编码,规格编码,仓库编码,合同号都一致),则不新增库存,加到同一类型库存上
            StockEntity sameTypeStock = getSameTypeStock(transferDetail);
            if (null == sameTypeStock) {
                //结果为空,则表明不存在同一类型库存数据,新增库存
                insertStockByTransfer(transfer, stockEntity, transferDetail);
                //新库存新增明细(调拨流水)
                insertStockDetail(transferQuantity, transfer, stockEntity);
            } else {
                //结果不为空,则表明存在同一类型库存数据,调拨审批后,库存不新增记录,只在同一类型库存信息上累加调拨数据
                //初始化库存对象
                StockEntity newStock = new StockEntity();
                //设置id
                newStock.setId(sameTypeStock.getId());
                //设置当前实际数量 = 原实际数量 + 调拨数量
                newStock.setRealQuantity(sameTypeStock.getRealQuantity().add(transferQuantity));
                //实际可用默认为零
                newStock.setRealAvailableQuantity(new BigDecimal("0.0000"));
                //设置当前可申请数量 = 原可申请数量 + 调拨数量
                newStock.setCanApplyQuantity(sameTypeStock.getCanApplyQuantity().add(transferQuantity));
                //设置总托盘 = 原总托盘 + 调拨总托盘
                BigDecimal nowTotalTray = sameTypeStock.getTotalTray().add(transferTotalTray);
                newStock.setTotalTray(nowTotalTray);
                //调用库存接口,更新最新库存信息
                stockService.update(newStock);
                //新库存新增明细(调拨流水)
                insertStockDetail(transferQuantity, transfer, newStock);
            }

        }
        //修改调拨的状态,改为已批箱
        TransferEntity transferEntity = new TransferEntity();
        transferEntity.setId(transferId);
        transferEntity.setStatus(OperationStatusEnum.APPROVED_BOX.getId());
        transferService.update(transferEntity);

        return R.build(ResultStatusEnum.SUCCESS);
    }

    /**
     * 置空审批
     *
     * @param transferId 调拨id
     * @return 审批结果
     */
    private R checkBlanking(Integer transferId) {
        //通过id获取调拨对象
        TransferEntity transfer = transferService.getTransferById(transferId);
        if (null == transfer) {
            LOGGER.warn("仓库管理-调拨-审核-获取调拨对象为空");
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }
        //初始化调拨明细对象
        TransferDetailEntity transferDetailReq = new TransferDetailEntity();
        //设置调拨id
        transferDetailReq.setTransferId(transferId);
        //设置数据有效性(0:无效 1:有效)
        transferDetailReq.setValid(DataIsValidEnum.VALID.getId());
        //查询调拨明细
        List<TransferDetailEntity> transferDetails = transferDetailService.queryAll(transferDetailReq);
        if (CollectionUtils.isEmpty(transferDetails)) {
            LOGGER.warn("仓库管理-调拨-审核-获取调拨明细对象为空");
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }
        for (TransferDetailEntity transferDetail : transferDetails) {
            //获取库存id
            Integer stockId = transferDetail.getStockId();
            //通过库存id获取库存信息
            StockEntity stockEntity = stockService.getStockById(stockId);
            //原始总托盘
            BigDecimal totalTray = stockEntity.getTotalTray();
            //调拨总托盘
            BigDecimal transferTotalTray = transferDetail.getTotalTray();
            //初始化库存对象
            StockEntity stock = new StockEntity();
            //设置库存id
            stock.setId(stockId);
            //更新后总托盘 = 原总托盘 - 调拨总托盘
            if (StringUtil.isNotEmpty(totalTray) && StringUtil.isNotEmpty(transferTotalTray)) {
                stock.setTotalTray(totalTray.subtract(transferTotalTray));
            }
            //原实际数量
            BigDecimal realQuantity = stockEntity.getRealQuantity();
            //原调拨申请数量
            BigDecimal transferApplyQuantity = new BigDecimal("0");
            if (StringUtil.isNotEmpty(stockEntity.getTransferApplyQuantity())) {
                transferApplyQuantity = stockEntity.getTransferApplyQuantity();
            }
            //调拨数量
            BigDecimal transferQuantity = transferDetail.getTransferQuantity();
            //更新后实际数量和实际可用数量 = 原实际数量 - 调拨数量
            if (StringUtil.isNotEmpty(realQuantity) && StringUtil.isNotEmpty(transferQuantity)) {
                BigDecimal quantity = realQuantity.subtract(transferQuantity);
                //更新实际数量
                stock.setRealQuantity(quantity);
                //更新调拨申请数量
                stock.setTransferApplyQuantity(transferApplyQuantity.subtract(transferQuantity));
            }

            //调用库存接口更新库存信息
            stockService.update(stock);

            //原库存新增明细(调拨流水)
            insertStockDetail(transferQuantity, transfer, stockEntity);

            //如果已存在同一类型库存数据(批次,产品编码,规格编码,仓库编码,合同号都一致),则不新增库存,加到同一类型库存上
            StockEntity sameTypeStock = getSameTypeStock(transferDetail);
            if (null == sameTypeStock) {
                //结果为空,则表明不存在同一类型库存数据,新增库存
                insertStockByBlankingAdd(transfer, stockEntity, transferDetail);
                //新库存新增明细(调拨流水)
                insertStockDetail(transferQuantity, transfer, stockEntity);
            } else {
                //结果不为空,则表明存在同一类型库存数据,调拨审批后,库存不新增记录,只在同一类型库存信息上累加调拨数据
                //初始化库存对象
                StockEntity newStock = new StockEntity();
                //设置id
                newStock.setId(sameTypeStock.getId());
                //设置当前实际数量 = 原实际数量 + 调拨数量
                newStock.setRealQuantity(sameTypeStock.getRealQuantity().add(transferQuantity));
                //设置当前可申请数量 = 原可申请数量 + 调拨数量
                newStock.setCanApplyQuantity(sameTypeStock.getCanApplyQuantity().add(transferQuantity));
                //设置总托盘 = 原总托盘 + 调拨总托盘
                BigDecimal oldTotalTray = new BigDecimal("0");
                if (StringUtil.isNotEmpty(sameTypeStock.getTotalTray())) {
                    oldTotalTray = sameTypeStock.getTotalTray();
                }
                BigDecimal nowTotalTray = oldTotalTray.add(transferTotalTray);
                newStock.setTotalTray(nowTotalTray);
                if (StringUtils.isEmpty(transferDetail.getNewContractNo())) {
                    //外销合同号
                    newStock.setContractNo(null);
                    //合同类型 待定
                    newStock.setContractType(ContractTypeEnum.TO_BE_DETERMINED.getId());
                    //实际可用数量 = 实际数量
                    newStock.setRealAvailableQuantity(sameTypeStock.getRealAvailableQuantity().add(transferQuantity));
                } else {
                    //外销合同号
                    newStock.setContractNo(transferDetail.getNewContractNo());
                    //合同类型 外销
                    newStock.setContractType(ContractTypeEnum.FOR_SALE_ABROAD.getId());
                }
                //调用库存接口,更新最新库存信息
                stockService.update(newStock);
                //新库存新增明细(调拨流水)
                insertStockDetail(transferQuantity, transfer, sameTypeStock);
            }

        }
        //修改调拨的状态,改为已批箱
        TransferEntity transferEntity = new TransferEntity();
        transferEntity.setId(transferId);
        transferEntity.setStatus(OperationStatusEnum.APPROVED_BOX.getId());
        transferService.update(transferEntity);

        return R.build(ResultStatusEnum.SUCCESS);
    }

    /**
     * 获取同类型库存数据
     *
     * @param transferDetail 调拨明细
     * @return 同类型库存对象
     */
    private StockEntity getSameTypeStock(TransferDetailEntity transferDetail) {
        //获取批次号
        String lotNo = transferDetail.getLotNo();
        //获取产品编码
        String productCode = transferDetail.getProductCode();
        //获取规格编码
        String specificationCode = transferDetail.getSpecificationCode();
        //初始化库存对象
        StockEntity req = new StockEntity();
        //设置批次号
        req.setLotNo(lotNo);
        //设置产品编码
        req.setProductCode(productCode);
        //设置规格编码
        req.setSpecificationCode(specificationCode);
        //设置新的仓库编码
        req.setWarehouseCode(transferDetail.getNewWarehouseCode());
        //设置新的合同号
        req.setContractNo(transferDetail.getNewContractNo());
        //通过库存接口查询库存对象集合
        List<StockEntity> stock = stockService.getTheSameStockInfo(req);
        if (CollectionUtils.isEmpty(stock)) {
            return null;
        } else {
            return stock.get(0);
        }
    }

    /**
     * 调拨审批后库存明细新增
     *
     * @param num      调拨数量
     * @param transfer 调拨对象
     * @param stock    库存对象
     */
    private void insertStockDetail(BigDecimal num, TransferEntity transfer, StockEntity stock) {
        StockDetailEntity stockDetail = new StockDetailEntity();
        //库存id
        stockDetail.setStockId(stock.getId());
        //标题
        stockDetail.setTitle(DataSourceTitleEnum.TRANSFER.getDesc());
        //模块id
        stockDetail.setModuleId(DataSourceTitleEnum.TRANSFER.getId());
        //单据编号(调拨单号)
        stockDetail.setInvoiceNumber(transfer.getBillNo());
        //仓库编码
        stockDetail.setWarehouseCode(transfer.getWarehouseCode());
        //仓库名称
        stockDetail.setWarehouseName(transfer.getWarehouseName());
        //产品编码
        stockDetail.setProductCode(stock.getProductCode());
        //规格编码
        stockDetail.setSpecificationCode(stock.getSpecificationCode());
        //颜色
        stockDetail.setColor(stock.getColor());
        //成本单价(初始来源于备货入库中的 入库成本)
        BigDecimal productUnitPrice = stock.getProductUnitPrice();
        stockDetail.setUnitPrice(productUnitPrice);
        //成本金额=成本单价*实际数量
        if (StringUtil.isNotEmpty(productUnitPrice) && StringUtil.isNotEmpty(num)) {
            stockDetail.setMoney(productUnitPrice.multiply(num));
        }
        //数量
        stockDetail.setQuantity(num);
        //标准单位数量
        stockDetail.setStandardUnitQuantity(num);
        //标准单位
        stockDetail.setStandardUnit(stock.getProductUnit());
        //创建时间
        stockDetail.setCreateDate(new Date());
        //入库人
        stockDetail.setInStorePerson(transfer.getCreator());
        //入库人编码
        stockDetail.setInStoreCode(transfer.getCreatorNo());
        //操作人
        stockDetail.setOperator(transfer.getCreator());
        //操作人编码
        stockDetail.setOperationCode(transfer.getCreatorNo());
        //规格说明
        stockDetail.setProductSpecExplanation(stock.getSpecificationExplanation());
        //备注(取调拨表里面的备注)
        stockDetail.setMemo(transfer.getMemo());
        //数据有效
        stockDetail.setValid(DataIsValidEnum.VALID.getId());

        //调用库存明细接口新增库存明细
        stockDetailService.insert(stockDetail);
    }

    /**
     * 调拨审批后新增库存信息
     *
     * @param transfer       调拨对象
     * @param stockEntity    原库存对象
     * @param transferDetail 调拨明细对象
     */
    private void insertStockByTransfer(TransferEntity transfer, StockEntity stockEntity, TransferDetailEntity transferDetail) {
        //调拨数量
        BigDecimal transferQuantity = transferDetail.getTransferQuantity();
        //更新父库存id
        stockEntity.setParentId(transferDetail.getStockId());
        //实际数量 = 调拨数量
        stockEntity.setRealQuantity(transferQuantity);
        //出库申请数量为零
        stockEntity.setOutWarehouseApply(new BigDecimal("0.0000"));
        //可申请数量 = 实际数量
        stockEntity.setCanApplyQuantity(transferQuantity);
        //获取新的合同号
        String newContractNo = transferDetail.getNewContractNo();
        //如果新合同号为空,且调拨类型为合同置空则合同号置空,合同类型为"待定",否则合同类型为"外销"
        //外销合同号
        stockEntity.setContractNo(transferDetail.getNewContractNo());
        //合同类型 外销
        stockEntity.setContractType(ContractTypeEnum.FOR_SALE_ABROAD.getId());
        //实际可用数量为零
        stockEntity.setRealAvailableQuantity(new BigDecimal("0.0000"));
        //调拨申请为零
        stockEntity.setTransferApplyQuantity(new BigDecimal("0.0000"));
        //仓库
        stockEntity.setWarehouseCode(transferDetail.getNewWarehouseCode());
        stockEntity.setWarehouseName(transferDetail.getNewWarehouseName());
        //成本金额 = 调拨金额
        stockEntity.setCostAmount(transferDetail.getMoney());
        //成本单价 = 调拨成本单价
        stockEntity.setProductUnitPrice(transferDetail.getCostUnitPrice());
        //分摊费用单价
        stockEntity.setShareCostPrice(transferDetail.getShareCostPrice());
        //备注
        stockEntity.setMemo(transfer.getMemo());
        //总托盘数为调拨总托盘数
        stockEntity.setTotalTray(transferDetail.getTotalTray());
        //创建时间
        stockEntity.setCreateDate(transfer.getCreateDate());
        //业务员
        stockEntity.setSalesman(transferDetail.getSalesmanName());
        //业务员编码
        stockEntity.setSalesmanCode(transferDetail.getSalesmanCode());

        //调用库存接口新增库存信息
        stockService.insert(stockEntity);
    }

    /**
     * 置空审批后新增库存信息
     *
     * @param transfer       置空对象
     * @param stockEntity    原库存对象
     * @param transferDetail 置空明细对象
     */
    private void insertStockByBlankingAdd(TransferEntity transfer, StockEntity stockEntity, TransferDetailEntity transferDetail) {
        //调拨数量
        BigDecimal transferQuantity = transferDetail.getTransferQuantity();
        //更新父库存id
        stockEntity.setParentId(transferDetail.getStockId());
        //实际数量 = 调拨数量
        stockEntity.setRealQuantity(transferQuantity);
        //出库申请数量为零
        stockEntity.setOutWarehouseApply(new BigDecimal("0.0000"));
        //可申请数量 = 实际数量
        stockEntity.setCanApplyQuantity(transferQuantity);
        //调拨申请
        stockEntity.setTransferApplyQuantity(new BigDecimal("0.0000"));
        if (StringUtils.isEmpty(transferDetail.getNewContractNo())) {
            //外销合同号
            stockEntity.setContractNo(null);
            //合同类型 待定
            stockEntity.setContractType(ContractTypeEnum.TO_BE_DETERMINED.getId());
            //实际可用数量 = 实际数量
            stockEntity.setRealAvailableQuantity(transferQuantity);
        } else {
            //外销合同号
            stockEntity.setContractNo(transferDetail.getNewContractNo());
            //合同类型 外销
            stockEntity.setContractType(ContractTypeEnum.FOR_SALE_ABROAD.getId());
            //实际可用数量 = 实际数量
            stockEntity.setRealAvailableQuantity(new BigDecimal("0.0000"));
        }

        //仓库
        stockEntity.setWarehouseCode(transferDetail.getNewWarehouseCode());
        stockEntity.setWarehouseName(transferDetail.getNewWarehouseName());
        //成本金额 = 调拨金额
        stockEntity.setCostAmount(transferDetail.getMoney());
        //成本单价 = 调拨成本单价
        stockEntity.setProductUnitPrice(transferDetail.getCostUnitPrice());
        //分摊费用单价
        stockEntity.setShareCostPrice(transferDetail.getShareCostPrice());
        //备注
        stockEntity.setMemo(transfer.getMemo());
        //总托盘数为调拨总托盘数
        stockEntity.setTotalTray(transferDetail.getTotalTray());
        //创建时间
        stockEntity.setCreateDate(transfer.getCreateDate());
        //业务员
        stockEntity.setSalesman(transfer.getCreator());
        //业务员编码
        stockEntity.setSalesmanCode(transfer.getCreatorNo());

        //调用库存接口新增库存信息
        stockService.insert(stockEntity);
    }

    /**
     * 合同置空
     *
     * @param req      新增参数对象
     * @param creator  创建人
     * @param createNo 创建人编码
     * @return 置空结果
     * @throws ParseException
     */
    @Transactional(rollbackFor = Exception.class)
    public R contractInitAdd(AddTransferReq req, String creator, String createNo) throws ParseException {
        //明细新合同号剔除前后空格
        setNewContractNoTrim(req.getTransferDetails());
        boolean billNoCheckFlag = (null != req.getId() && req.getBillNo().equals(req.getNewBillNo()));
        if (!billNoCheckFlag) {
            //单号做唯一校验
            boolean billNoFlag = checkRepeatBillNo(req.getBillNo());
            if (!billNoFlag) {
                return R.buildError(ResultStatusEnum.BILL_NO_REPEAT);
            }
        }
        if (!CollectionUtils.isEmpty(req.getTransferDetails())) {
            //是否可置空校验
            if (!checkTransferData(req)) {
                return R.buildError(ResultStatusEnum.TRANSFER_INFO_CHECK_ERROR);
            }
            //合同置空数量校验
            if (checkTransferNum(req)) {
                return R.buildError(ResultStatusEnum.TRANSFER_QUANTITY_CHECK_ERROR);
            }
        }

        //新增调拨信息
        Integer transferId = insertTransfer(req, creator, createNo, req.getType());
        if (transferId == null) {
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }
        //调拨明细新增以及更新库存可申请数量
        insertTransferDetail(req, transferId, creator, createNo);
        //添加附件信息
        boolean flag = addAnnex(req.getAnnexReqs(), transferId, creator, createNo);
        if (!flag) {
            LOGGER.info("仓库管理-调拨-合同置空-批量新增附件异常");
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }
        //删除临时附件信息
        deleteTempAnnex(req.getAnnexReqs());

        return R.build(ResultStatusEnum.SUCCESS);
    }

    /**
     * 明细新合同号剔除前后空格
     * @param req 明细数据对象集合
     */
    private void setNewContractNoTrim(List<AddTransferDetailReq> req) {
        if (CollectionUtils.isEmpty(req)) {
            return;
        }
        for (AddTransferDetailReq detail : req) {
            String oldContractNo = detail.getNewContractNo();
            //剔除前后空格
            if (StringUtils.isNotEmpty(oldContractNo)) {
                String newContractNo = oldContractNo.trim();
                detail.setNewContractNo(newContractNo);
            }
        }
    }

    /**
     * 校验单号是否存在
     *
     * @param billNo 单号
     * @return true:不重复 false:重复
     */
    private boolean checkRepeatBillNo(String billNo) {
        QueryTransferReq req = new QueryTransferReq();
        req.setBillNo(billNo);
        List<TransferEntity> transferList = transferService.queryTransferList(req);
        if (CollectionUtils.isEmpty(transferList)) {
            return true;
        }
        return false;
    }

    /**
     * 批量处理临时附件信息，将临时附件设置为失效
     *
     * @param annexReqs
     */
    private void deleteTempAnnex(List<AnnexReq> annexReqs) {
        //没有附件
        if (CollectionUtils.isEmpty(annexReqs)) {
            return;
        }
        //存在附件
        for (AnnexReq annex : annexReqs) {
            if (null != annex.getNews()) {
                //旧附件,不用修改
                continue;
            }
            TempAnnexEntity tempAnnex = new TempAnnexEntity();
            //设置临时附件id
            tempAnnex.setId(annex.getId());
            //设置修改时间
            tempAnnex.setUpdateTime(new Date());
            //将附件设置为失效
            tempAnnex.setValid(0);
            tempAnnexService.update(tempAnnex);
        }

    }

    /**
     * 附件新增
     *
     * @param annexReqs  附件信息
     * @param transferId 调拨id
     * @param operator   操作人
     * @param operatorNo 操作人编码
     * @return 是否新增成功(true : 成功 false : 失败)
     */
    private boolean addAnnex(List<AnnexReq> annexReqs, Integer transferId, String operator, String operatorNo) {
        try {
            //没有附件,不新增
            if (CollectionUtils.isEmpty(annexReqs)) {
                return true;
            }
            //存在附件,新增附件信息
            List<AnnexEntity> list = new ArrayList<>();
            //获取旧的附件id集合
            List<Integer> oldIds = new ArrayList<>();
            for (AnnexReq annexReq : annexReqs) {
                if (null != annexReq.getNews()) {
                    //属于旧附件 只取id,不新增
                    oldIds.add(annexReq.getId());
                    continue;
                }
                AnnexEntity annex = new AnnexEntity();
                BeanUtils.copyProperties(annexReq, annex);
                //设置关联模块id
                annex.setModuleId(ModuleTypeEnum.WAREHOUSE_TRANSFER.getId());
                //设置关联模块父id
                annex.setParentId(transferId);
                //设置上传时间
                annex.setUploadTime(DateUtils.convertStringToDate(annexReq.getUploadTime(), DateUtils.DATE_TIME_PATTERN));
                //设置修改时间
                annex.setUpdateTime(new Date());
                //设置操作人
                annex.setOperator(operator);
                //设置操作人编码
                annex.setOperatorNo(operatorNo);
                //设置数据有效
                annex.setValid(1);

                list.add(annex);
            }
            if (oldIds.size() > 0) {
                //通过调拨id获取修改附件信息
                AnnexEntity annex = new AnnexEntity();
                annex.setModuleId(ModuleTypeEnum.WAREHOUSE_TRANSFER.getId());
                annex.setParentId(transferId);
                //获取上次附件信息
                List<AnnexEntity> annexList = annexService.queryAll(annex);
                if (!CollectionUtils.isEmpty(annexList)) {
                    //获取上次附件id集合
                    List<Integer> oldAnnexIds = annexList.stream().map(p -> p.getId()).collect(Collectors.toList());
                    //得到被删除的附件id
                    Collection collection = new ArrayList(oldAnnexIds);
                    collection.removeAll(oldIds);
                    if (collection.size() > 0) {
                        Iterator<Integer> it = collection.iterator();
                        while (it.hasNext()) {
                            int id = it.next();
                            AnnexEntity annexEntity = new AnnexEntity();
                            annexEntity.setId(id);
                            //将被删除的附件设为失效
                            annexEntity.setValid(DataIsValidEnum.INVALID.getId());

                            annexService.update(annexEntity);
                        }
                    }
                }
            }
            if (!CollectionUtils.isEmpty(list)) {
                //附件批量新增
                int res = annexService.batchInsert(list);
                if (res == list.size()) {
                    return true;
                }
            }
            return true;
        } catch (Exception e) {
            throw new RuntimeException();
        }
    }


    /**
     * 整个调拨单作废
     *
     * @param transferId 调拨id
     * @return 作废信息
     */
    public R invoiceBatchInvalid(Integer transferId) {
        //通过调拨id获取调拨明细
        if (null == transferId) {
            LOGGER.warn("仓库管理-调拨--单据作废-调拨id为空");
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }
        //初始化调拨明细对象
        TransferDetailEntity req = new TransferDetailEntity();
        //设置调拨id
        req.setTransferId(transferId);
        //设置数据有效性(0:无效 1:有效)
        req.setValid(DataIsValidEnum.VALID.getId());
        //查询调拨明细
        List<TransferDetailEntity> transferDetails = transferDetailService.queryAll(req);
        if (transferDetails.isEmpty()) {
            LOGGER.warn("仓库管理-调拨-单据作废-获取调拨明细对象为空");
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }
        for (TransferDetailEntity transferDetail : transferDetails) {
            boolean flag = checkInvoiceInvalid(transferDetail);
            if (!flag) {
                //单据无法作废
                return R.buildError(ResultStatusEnum.TRANSFER_INVOICE_INVALID_ERROR);
            }
        }
        return R.build(ResultStatusEnum.SUCCESS);
    }

    /**
     * 单条调拨单作废
     *
     * @param transferDetailId 调拨明细id
     * @return 作废信息
     */
    public R invoiceInvalid(Integer transferDetailId) {
        if (null == transferDetailId) {
            LOGGER.warn("仓库管理-调拨--单条单据作废-调拨明细id为空");
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }
        TransferDetailEntity transferDetail = transferDetailService.getTransferDetailById(transferDetailId);
        //作废校验
        boolean flag = checkInvoiceInvalid(transferDetail);
        if (!flag) {
            //单据无法作废
            return R.buildError(ResultStatusEnum.TRANSFER_INVOICE_INVALID_ERROR);
        }

        return R.build(ResultStatusEnum.SUCCESS);
    }


    /**
     * 校验单据是否成功作废
     *
     * @param transferDetail 调拨明细
     * @return 作废状态
     */
    public boolean checkInvoiceInvalid(TransferDetailEntity transferDetail) {
        //通过库存id获取库存信息
        StockEntity stock = stockService.getStockById(transferDetail.getStockId());
        //获取调拨数量
        BigDecimal transferQuantity = transferDetail.getTransferQuantity();
        //获取库存实际数量
        BigDecimal realQuantity = stock.getRealQuantity();
        //库存实际数量大于等于调拨数量时,此单据才可作废,否则不允许作废
        boolean flag = transferQuantity.compareTo(realQuantity) == -1;
        if (!flag) {
            //单据无法作废
            return false;
        }
        //单据作废,数据回退
        StockEntity stockEntity = new StockEntity();
        //设置id
        stockEntity.setId(stock.getId());
        //设置作废后实际数量 = 作废前实际数量 + 调拨数量
        stockEntity.setRealQuantity(realQuantity.add(transferQuantity));
        //设置可申请数量
        stockEntity.setCanApplyQuantity(stock.getCanApplyQuantity().add(transferQuantity));
        if (stock.getContractType() == ContractTypeEnum.TO_BE_DETERMINED.getId()) {
            //如果合同类型为待定,则实际可用数量也需要回退
            stockEntity.setRealAvailableQuantity(stock.getRealAvailableQuantity().add(transferQuantity));
        }
        //设置总托盘 = 原总托盘 + 调拨总托盘
        BigDecimal nowTotalTray = stock.getTotalTray().add(transferDetail.getTotalTray());
        stockEntity.setTotalTray(nowTotalTray);
        //调用库存接口进行数据更新
        stockService.update(stockEntity);

        //同时将该调拨明细数据状态改为失效
        TransferDetailEntity detail = new TransferDetailEntity();
        //设置修改id
        detail.setId(transferDetail.getId());
        //设置状态为无效
        detail.setValid(DataIsValidEnum.INVALID.getId());
        //调用调拨明细接口更新数据
        transferDetailService.update(detail);

        return true;
    }


    /**
     * 调拨数据操作接口
     *
     * @param req 操作对象
     *            1.提交审批 2.审批通过 3.审批退回 4.完成 5.还原
     *            箱体：1.草稿箱 2.待批箱 3.已批箱 4.完成箱 5.垃圾箱
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public R operationTransfer(OperationReq req) {
        Integer id = req.getId();
        Integer operation = req.getOperation();
        if (null == id) {
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }
        TransferEntity transfer = new TransferEntity();
        //设置id
        transfer.setId(id);
        if (operation == SubmitStatusEnum.SUBMIT_APPROVE.getId()) {
            //审批通过后,状态为已审批,库存实际数量和实际可用数量需要减掉
            if (2 == req.getTransferType()) {
                //合同置空
                //将状态改为已批箱
                transfer.setStatus(OperationStatusEnum.APPROVED_BOX.getId());
                return checkBlanking(id);
            } else {
                //合同调拨
                return checkTransfer(id);
            }
        } else if (operation == SubmitStatusEnum.APPROVE_SUCCESS.getId()) {

        } else if (operation == SubmitStatusEnum.APPROVE_RETURN.getId()) {

        } else if (operation == SubmitStatusEnum.SUCCESS.getId()) {
            //将状态设为完成
            transfer.setStatus(OperationStatusEnum.COMPLETION_BOX.getId());
        } else if (operation == SubmitStatusEnum.REDUCTION.getId()) {
            //将状态改为草稿箱
            transfer.setStatus(OperationStatusEnum.DRAFT_BOX.getId());
        }
        //修改数据
        transferService.update(transfer);
        return R.build("");
    }

    /**
     * 获取所有仓库字典信息
     *
     * @return 仓库字典信息
     */
    public List<DictionaryInfoVo> getAllWarehouseInfo() {
        //初始化回参
        List<DictionaryInfoVo> warehouseVos = new ArrayList<>();
        //获取所有仓库字典信息
        DictionaryInfoReq dictionaryInfosReq = new DictionaryInfoReq();
        //仓库维护
        dictionaryInfosReq.setType(DictionaryTypeEnum.WAREHOUSE_MAINTENANCE.getId());
        //主仓库维护
        dictionaryInfosReq.setLx(DictionaryLxEnum.MAIN_WAREHOUSE_MAINTENANCE.getId());
        List<DictionaryInfoRsp> warehouseInfos = stockService.getDictionaryInfo(dictionaryInfosReq);
        if (CollectionUtils.isEmpty(warehouseInfos)) {
            return warehouseVos;
        }
        for (DictionaryInfoRsp infoRsp : warehouseInfos) {
            DictionaryInfoVo vo = new DictionaryInfoVo();
            BeanUtils.copyProperties(infoRsp, vo);

            warehouseVos.add(vo);
        }

        return warehouseVos;
    }


    /**
     * 调拨新增
     *
     * @param req      新增参数对象
     * @param creator  创建人
     * @param createNo 创建人编码
     * @return 新增调拨结果
     * @throws ParseException
     */
    @Transactional(rollbackFor = Exception.class)
    public R addTransfer(AddTransferReq req, String creator, String createNo) throws ParseException {
        //单号做唯一校验
        boolean billNoFlag = checkRepeatBillNo(req.getBillNo());
        if (!billNoFlag) {
            return R.buildError(ResultStatusEnum.BILL_NO_REPEAT);
        }
        if (!CollectionUtils.isEmpty(req.getTransferDetails())) {
            //数量校验
            if (checkTransferNum(req)) {
                return R.buildError(ResultStatusEnum.TRANSFER_QUANTITY_CHECK_ERROR);
            }
        }

        //新增调拨信息
        Integer transferId = insertTransferEntity(req, creator, createNo);
        if (transferId == null) {
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }
        //调拨明细新增以及更新库存可申请数量
        insertTransferDetailEntity(req, transferId, creator, createNo);
        //添加附件信息
        boolean flag = addAnnexByTransferAdd(req.getAnnexReqs(), transferId, creator, createNo);
        if (!flag) {
            LOGGER.info("仓库管理-调拨-合同置空-批量新增附件异常");
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }
        //删除临时附件信息
        deleteTempAnnex(req.getAnnexReqs());

        return R.build(ResultStatusEnum.SUCCESS);
    }

    /**
     * 调拨明细新增以及更新库存可申请数量
     *
     * @param req        新增对象
     * @param transferId 调拨id
     */
    public void insertTransferDetailEntity(AddTransferReq req, int transferId, String creator, String createNo) {
        if (!CollectionUtils.isEmpty(req.getTransferDetails())) {
            //获取修改调拨明细id集合
            List<Integer> newIds = new ArrayList<>();
            //新增调拨明细集合
            List<TransferDetailEntity> addTransferDetails = new ArrayList<>();
            for (AddTransferDetailReq detailReq : req.getTransferDetails()) {
                //初始化调拨明细对象
                TransferDetailEntity transferDetail = new TransferDetailEntity();
                //赋值
                BeanUtils.copyProperties(detailReq, transferDetail);
                //设置调拨id
                transferDetail.setTransferId(transferId);
                //业务员名称
                if(StringUtils.isNotEmpty(detailReq.getSalesman())){
                    transferDetail.setSalesmanName(detailReq.getSalesman());
                }
                //分摊费用单价
                BigDecimal shareCostPrice = new BigDecimal("0");
                if (StringUtil.isNotEmpty(detailReq.getShareCostPrice())) {
                    shareCostPrice = detailReq.getShareCostPrice();
                }
                //成本单价
                BigDecimal costUnitPrice = new BigDecimal("0");
                if (StringUtil.isNotEmpty(detailReq.getCostUnitPrice())) {
                    costUnitPrice = detailReq.getCostUnitPrice();
                }
                //获取调拨数量
                BigDecimal transferQuantity = new BigDecimal("0");
                if (StringUtil.isNotEmpty(detailReq.getTransferQuantity())) {
                    transferQuantity = detailReq.getTransferQuantity();
                }

                //设置金额 = (分摊费用单价 + 成本单价)*调拨数量
                if (StringUtil.isNotEmpty(costUnitPrice)) {
                    BigDecimal cost = shareCostPrice.add(costUnitPrice);
                    transferDetail.setMoney(cost.multiply(transferQuantity));
                }
                //获取托盘入数
                BigDecimal trayNumber = new BigDecimal("0");
                if (StringUtil.isNotEmpty(detailReq.getTrayNumber())) {
                    trayNumber = detailReq.getTrayNumber();
                }
                if (StringUtil.isNotEmpty(trayNumber)) {
                    //设置总托盘 = 调拨数量除以托盘入数
                    transferDetail.setTotalTray(transferQuantity.divide(trayNumber, 2, BigDecimal.ROUND_HALF_UP));
                } else {
                    transferDetail.setTotalTray(new BigDecimal("0"));
                }

                //设置数据有效性(0:无效 1:有效)
                transferDetail.setValid(DataIsValidEnum.VALID.getId());

                //库存明细新增
                int stockDetailId = addStockDetailByTransferAdd(detailReq, req.getBillNo(), creator, createNo);
                //修改库存信息
                updateStockInfoByTransferAdd(detailReq);

                //设置明细库存id
                transferDetail.setStockDetailId(stockDetailId);
                addTransferDetails.add(transferDetail);

            }

            if (!CollectionUtils.isEmpty(addTransferDetails)) {
                //调用接口保存调拨明细
                transferDetailService.insertTransferDetailList(addTransferDetails);
            }
        }
    }

    /**
     * 新增调拨主表信息
     *
     * @param req      新增参数
     * @param creator  创建人
     * @param createNo 创建人编码
     * @return 调拨id
     * @throws ParseException
     */
    public Integer insertTransferEntity(AddTransferReq req, String creator, String createNo) throws ParseException {
        //初始化调拨对象
        TransferEntity transfer = new TransferEntity();
        //赋值
        BeanUtils.copyProperties(req, transfer);
        //设置调拨类型(1:合同调拨 2:合同置空)
        transfer.setType(TransferTypeEnum.CONTRACT_TRANSFER.getId());
        //设置调拨时间
        transfer.setTime(DateUtils.convertStringToDate(req.getTime(), DateUtils.DATE_PATTERN));
        //设置创建人
        transfer.setCreator(creator);
        //设置创建人编码
        transfer.setCreatorNo(createNo);
        //保存后进草稿箱
        transfer.setStatus(OperationStatusEnum.DRAFT_BOX.getId());
        //设置数据有效性(0:无效 1:有效)
        transfer.setValid(DataIsValidEnum.VALID.getId());
        //设置创建时间
        transfer.setCreateDate(new Date());
        //调用接口新增调拨
        return transferService.insert(transfer) == 1 ? transfer.getId() : null;
    }

    /**
     * 新增库存明细
     *
     * @param detailReq 调拨明细
     * @param billNo    单号
     * @param creator   创建人
     * @param createNo  创建人编码
     */
    private int addStockDetailByTransferAdd(AddTransferDetailReq detailReq, String billNo, String creator, String createNo) {
        //初始化库存明细对象
        StockDetailEntity stockDetail = new StockDetailEntity();
        //赋值
        BeanUtils.copyProperties(detailReq, stockDetail);
        //设置标题
        stockDetail.setTitle(DataSourceTitleEnum.TRANSFER.getDesc());
        //设置单据编号
        stockDetail.setInvoiceNumber(billNo);
        //设置单价
        stockDetail.setUnitPrice(detailReq.getCostUnitPrice());
        //设置数量
        stockDetail.setQuantity(detailReq.getTransferQuantity());
        //设置模块id
        stockDetail.setModuleId(ModuleTypeEnum.WAREHOUSE_TRANSFER.getId());
        //设置创建人
        stockDetail.setInStorePerson(creator);
        //设置创建人编码
        stockDetail.setInStoreCode(createNo);
        //设置操作人
        stockDetail.setOperator(creator);
        //设置操作人编码
        stockDetail.setOperationCode(createNo);
        //设置创建时间
        stockDetail.setCreateDate(new Date());
        //设置有效性
        stockDetail.setValid(DataIsValidEnum.VALID.getId());
        stockDetailService.insert(stockDetail);

        return stockDetail.getId();
    }

    /**
     * 修改库存信息
     *
     * @param detailReq
     */
    private void updateStockInfoByTransferAdd(AddTransferDetailReq detailReq) {
        //获取库存数据
        StockEntity stockInfo = stockService.getStockById(detailReq.getStockId());
        //获取调拨数量
        BigDecimal transferQuantity = detailReq.getTransferQuantity();
        //获取库存可申请数量
        BigDecimal canApplyQuantity = stockInfo.getCanApplyQuantity();
        //获取库存调拨申请数量
        BigDecimal transferApplyQuantity = stockInfo.getTransferApplyQuantity();
        //初始化库存对象
        StockEntity stock = new StockEntity();
        //设置修改id
        stock.setId(detailReq.getStockId());
        stock.setCanApplyQuantity(canApplyQuantity.subtract(transferQuantity));
        stock.setTransferApplyQuantity(transferApplyQuantity.add(transferQuantity));
        stockService.update(stock);
    }

    /**
     * 合同调拨附件新增
     *
     * @param annexReqs  附件信息
     * @param transferId 调拨id
     * @param operator   操作人
     * @param operatorNo 操作人编码
     * @return 是否新增成功(true : 成功 false : 失败)
     */
    private boolean addAnnexByTransferAdd(List<AnnexReq> annexReqs, Integer transferId, String operator, String operatorNo) {
        try {
            //没有附件,不新增
            if (CollectionUtils.isEmpty(annexReqs)) {
                return true;
            }
            //存在附件,新增附件信息
            List<AnnexEntity> list = new ArrayList<>();
            for (AnnexReq annexReq : annexReqs) {
                AnnexEntity annex = new AnnexEntity();
                BeanUtils.copyProperties(annexReq, annex);
                //设置关联模块id
                annex.setModuleId(ModuleTypeEnum.WAREHOUSE_TRANSFER.getId());
                //设置关联模块父id
                annex.setParentId(transferId);
                //设置上传时间
                annex.setUploadTime(DateUtils.convertStringToDate(annexReq.getUploadTime(), DateUtils.DATE_TIME_PATTERN));
                //设置修改时间
                annex.setUpdateTime(new Date());
                //设置操作人
                annex.setOperator(operator);
                //设置操作人编码
                annex.setOperatorNo(operatorNo);
                //设置数据有效
                annex.setValid(1);

                list.add(annex);
            }
            if (!CollectionUtils.isEmpty(list)) {
                //附件批量新增
                annexService.batchInsert(list);
            }
            return true;
        } catch (Exception e) {
            throw new RuntimeException();
        }
    }

    /**
     * 调拨修改
     *
     * @param req      调拨修改对象
     * @param creator  创建人
     * @param createNo 创建人编码
     * @return 调拨修改结果
     * @throws ParseException
     */
    @Transactional(rollbackFor = Exception.class)
    public R updateTransfer(AddTransferReq req, String creator, String createNo) throws ParseException {
        boolean billNoCheckFlag = (null != req.getId() && req.getBillNo().equals(req.getNewBillNo()));
        if (!CollectionUtils.isEmpty(req.getTransferDetails())) {
            //合同置空数量校验
            if (checkTransferNum(req)) {
                return R.buildError(ResultStatusEnum.TRANSFER_QUANTITY_CHECK_ERROR);
            }
        }

        //新增调拨信息
        Integer transferId = insertTransfer(req, creator, createNo, req.getType());
        if (transferId == null) {
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }
        //调拨明细新增以及更新库存可申请数量
        insertTransferDetail(req, transferId, creator, createNo);
        //添加附件信息
        boolean flag = addAnnex(req.getAnnexReqs(), transferId, creator, createNo);
        if (!flag) {
            LOGGER.info("仓库管理-调拨-合同置空-批量新增附件异常");
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }
        //删除临时附件信息
        deleteTempAnnex(req.getAnnexReqs());

        return R.build(ResultStatusEnum.SUCCESS);
    }

    /**
     * 置空新增
     *
     * @param req      新增参数对象
     * @param creator  创建人
     * @param createNo 创建人编码
     * @return 置空结果
     * @throws ParseException
     */
    @Transactional(rollbackFor = Exception.class)
    public R addBlanking(AddTransferReq req, String creator, String createNo) throws ParseException {
        //明细新合同号剔除前后空格
        setNewContractNoTrim(req.getTransferDetails());
        //单号做唯一校验
        boolean billNoFlag = checkRepeatBillNo(req.getBillNo());
        if (!billNoFlag) {
            return R.buildError(ResultStatusEnum.BILL_NO_REPEAT);
        }
        if (!CollectionUtils.isEmpty(req.getTransferDetails())) {
            //是否可置空校验
            if (!checkTransferData(req)) {
                return R.buildError(ResultStatusEnum.TRANSFER_INFO_CHECK_ERROR);
            }
            //合同置空数量校验
            if (checkTransferNum(req)) {
                return R.buildError(ResultStatusEnum.TRANSFER_QUANTITY_CHECK_ERROR);
            }
        }

        //新增置空信息
        Integer transferId = insertBlanking(req, creator, createNo);
        if (transferId == null) {
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }

        //调拨明细新增以及更新库存可申请数量
        insertBlankingDetail(req, transferId, creator, createNo);
        //添加附件信息
        boolean flag = addAnnex(req.getAnnexReqs(), transferId, creator, createNo);
        if (!flag) {
            LOGGER.info("仓库管理-调拨-合同置空-批量新增附件异常");
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }
        //删除临时附件信息
        deleteTempAnnex(req.getAnnexReqs());

        return R.build(ResultStatusEnum.SUCCESS);
    }

    /**
     * 合同置空新增
     *
     * @param req      新增参数
     * @param creator  创建人
     * @param createNo 创建人编码
     * @return 置空id
     * @throws ParseException
     */
    public Integer insertBlanking(AddTransferReq req, String creator, String createNo) throws ParseException {
        //初始化调拨对象
        TransferEntity transfer = new TransferEntity();
        //赋值
        BeanUtils.copyProperties(req, transfer);
        //设置调拨类型(1:合同调拨 2:合同置空)
        transfer.setType(TransferTypeEnum.CONTRACT_INIT.getId());
        //设置调拨时间
        transfer.setTime(DateUtils.convertStringToDate(req.getTime(), DateUtils.DATE_PATTERN));
        //设置创建人
        transfer.setCreator(creator);
        //设置创建人编码
        transfer.setCreatorNo(createNo);
        //保存后进草稿箱
        transfer.setStatus(OperationStatusEnum.DRAFT_BOX.getId());
        //设置数据有效性(0:无效 1:有效)
        transfer.setValid(DataIsValidEnum.VALID.getId());
        //设置创建时间
        transfer.setCreateDate(new Date());
        //调用接口新增调拨
        return transferService.insert(transfer) == 1 ? transfer.getId() : null;

    }

    /**
     * 置空新增
     * 1.回退调拨明细表中调拨数量
     * 2.回退库存数据
     *
     * @param req        新增对象
     * @param transferId 调拨id
     */
    public void insertBlankingDetail(AddTransferReq req, int transferId, String creator, String createNo) {
        if (!CollectionUtils.isEmpty(req.getTransferDetails())) {
            //获取修改调拨明细id集合
            List<Integer> newIds = new ArrayList<>();
            //新增调拨明细集合
            List<TransferDetailEntity> addTransferDetails = new ArrayList<>();
            for (AddTransferDetailReq detailReq : req.getTransferDetails()) {
                //初始化调拨明细对象
                TransferDetailEntity transferDetail = new TransferDetailEntity();
                //赋值
                BeanUtils.copyProperties(detailReq, transferDetail);
                //设置调拨id
                transferDetail.setTransferId(transferId);
                //分摊费用单价
                BigDecimal shareCostPrice = new BigDecimal("0");
                if (StringUtil.isNotEmpty(detailReq.getShareCostPrice())) {
                    shareCostPrice = detailReq.getShareCostPrice();
                }
                //成本单价
                BigDecimal costUnitPrice = new BigDecimal("0");
                if (StringUtil.isNotEmpty(detailReq.getCostUnitPrice())) {
                    costUnitPrice = detailReq.getCostUnitPrice();
                }
                //获取调拨数量
                BigDecimal transferQuantity = new BigDecimal("0");
                if (StringUtil.isNotEmpty(detailReq.getTransferQuantity())) {
                    transferQuantity = detailReq.getTransferQuantity();
                }

                //设置金额 = (分摊费用单价 + 成本单价)*调拨数量
                if (StringUtil.isNotEmpty(costUnitPrice)) {
                    BigDecimal cost = shareCostPrice.add(costUnitPrice);
                    transferDetail.setMoney(cost.multiply(transferQuantity));
                }
                //获取托盘入数
                BigDecimal trayNumber = new BigDecimal("0");
                if (StringUtil.isNotEmpty(detailReq.getTrayNumber())) {
                    trayNumber = detailReq.getTrayNumber();
                }
                if (StringUtil.isNotEmpty(trayNumber)) {
                    //设置总托盘 = 调拨数量除以托盘入数
                    transferDetail.setTotalTray(transferQuantity.divide(trayNumber, 2, BigDecimal.ROUND_HALF_UP));
                } else {
                    transferDetail.setTotalTray(new BigDecimal("0"));
                }

                //设置数据有效性(0:无效 1:有效)
                transferDetail.setValid(DataIsValidEnum.VALID.getId());

                //库存明细新增
                int stockDetailId = addStockDetailByTransferAdd(detailReq, req.getBillNo(), creator, createNo);
                //修改库存信息
                updateStockInfoByBlanking(detailReq);

                //设置明细库存id
                transferDetail.setStockDetailId(stockDetailId);
                addTransferDetails.add(transferDetail);

            }

            if (!CollectionUtils.isEmpty(addTransferDetails)) {
                //调用接口保存调拨明细
                transferDetailService.insertTransferDetailList(addTransferDetails);
            }
        }
    }

    /**
     * 修改库存信息
     *
     * @param detailReq
     */
    private void updateStockInfoByBlanking(AddTransferDetailReq detailReq) {
        //获取调拨数量
        BigDecimal transferQuantity = detailReq.getTransferQuantity();
        if (StringUtil.isNotEmpty(transferQuantity)) {
            //获取库存信息
            StockEntity stockInfo = stockService.getStockById(detailReq.getStockId());
            //库存调拨申请数量
            BigDecimal transferApplyQuantity = stockInfo.getTransferApplyQuantity();
            //库存可申请数量
            BigDecimal canApplyQuantity = stockInfo.getCanApplyQuantity();

            //初始化库存对象
            StockEntity stock = new StockEntity();
            //设置修改id
            stock.setId(detailReq.getStockId());
            stock.setTransferApplyQuantity(transferApplyQuantity.add(transferQuantity));
            stock.setCanApplyQuantity(canApplyQuantity.subtract(transferQuantity));
            stockService.update(stock);

        }
    }

    /**
     * 外销调拨明细统计
     *
     * @param req 查询条件
     * @return 外销调拨明细统计
     */
    public PageInfo<StatisticsTransferAndContractInfoVo> statisticsTransferAndContract(StatisticsTransferAndContractInfoReq req) {
        //初始化回参
        List<StatisticsTransferAndContractInfoVo> voList = new ArrayList<>();
        //获取统计信息
        List<StatisticsTransferAndContractInfoRsp> statistics = transferService.statisticsTransferAndContractInfo(req);
        if (CollectionUtils.isEmpty(statistics)) {
            PageInfo pageInfo = new PageInfo();
            pageInfo.setList(voList);
            return pageInfo;
        }
        //获取分页信息
        PageInfo pageInfo = new PageInfo(statistics);
        for (StatisticsTransferAndContractInfoRsp info : statistics) {
            //初始化回参对象
            StatisticsTransferAndContractInfoVo vo = new StatisticsTransferAndContractInfoVo();
            //赋值
            BeanUtils.copyProperties(info, vo);
            //签约日期
            vo.setSigningDate(DateUtils.format(info.getSigningDate()));
            //销售数量
            BigDecimal productNum = new BigDecimal("0");
            if (StringUtil.isNotEmpty(info.getProductNum())) {
                productNum = info.getProductNum();
            }
            //已调拨数量
            BigDecimal transferNum = new BigDecimal("0");
            if (StringUtil.isNotEmpty(info.getTransferNum())) {
                transferNum = info.getTransferNum();
            }
            //未调拨数量 = 销售数量-已调拨数量
            BigDecimal unTransferNum = productNum.subtract(transferNum);
            vo.setUnTransferNum(unTransferNum);

            voList.add(vo);
        }
        pageInfo.setList(voList);
        return pageInfo;
    }

    /**
     * 调拨仓库入库详情统计
     * @param req 查询条件
     * @return 调拨仓库入库详情统计
     */
    public PageInfo<StatisticsTransferInStockInfoVo> getStatisticsTransferInStockInfo(StatisticsTransferInStockInfoReq req){
        //默认查询只包含"入库结尾"的单据
        StringBuilder billNo = new StringBuilder();
        if(StringUtils.isNotEmpty(req.getBillNo())){
            //单号去除前后空格
            billNo.append(req.getBillNo().trim());
        }
        boolean flag = StringUtils.isNotEmpty(req.getBillNo()) && (req.getBillNo().trim().contains("入") || req.getBillNo().trim().contains("入库"));
        if(!flag){
            billNo.append("入库");
        }
        req.setBillNo(billNo.toString());

        //调用接口查询结果
        List<StatisticsTransferInStockInfoRsp> statisticsTransferInStockInfo = transferService.getStatisticsTransferInStockInfo(req);
        PageInfo pageInfo = new PageInfo(statisticsTransferInStockInfo);
        if (CollectionUtils.isEmpty(statisticsTransferInStockInfo)) {
            pageInfo.setList(statisticsTransferInStockInfo);
            return pageInfo;
        }
        List<StatisticsTransferInStockInfoVo> voList = new ArrayList<>();
        for(StatisticsTransferInStockInfoRsp infoRsp : statisticsTransferInStockInfo){
            StatisticsTransferInStockInfoVo vo = new StatisticsTransferInStockInfoVo();
            //对象赋值
            BeanUtils.copyProperties(infoRsp, vo);
            //处理调拨类型(1:合同调拨 2:合同置空)
            vo.setType(TransferTypeEnum.getDescById(infoRsp.getType()));
            //调拨时间转换
            vo.setTime(DateUtils.format(infoRsp.getTime(), DateUtils.DATE_PATTERN));
            //创建时间转换
            vo.setCreateDate(DateUtils.format(infoRsp.getCreateDate(), DateUtils.DATE_PATTERN));

            voList.add(vo);
        }
        pageInfo.setList(voList);
        return pageInfo;
    }

}
